-----------------------------------------------------------------------------
-- 选择服务器界面
--
---------------
-- Author: 筱迪
-- Date: 2020.12.21
-----------------------------------------------------------------------------
require "Common/define"
require "Logic/Config"

UIServer = UIBase.New(PanelResNames.UIServer)
local this = UIServer

local _MServerInfo = Class("")
function _MServerInfo:Update(id,db)
    self.serverId = id
    self.name = db[1]
    self.ip = db[3]
    self.gamePort = db[4]   --游戏服端口
    self.loginUrl = db[5]   --登录服地址
    self.state = db[6]      -- 服务器状态
    self.version = db[7]
    self.time = db[8]
    self.showServerId = db[9]  --展示的服务器id，运营去配的
end

local ENU_CTRL_SHOW =
{
    HIDE = 0,
    SHOW = 1,
}
local ENU_TAB =
{
    RECOMMEND = 0, --推荐服务器
    ALL = 1, --全部服务器
}
local selectObj = nil
local DEBUG = false
function UIServer.Init()
    UIBase.Init(this)
end

function UIServer:OnCreate()
    self.serverTabNum = 1;
    self.btnClose = self:GetChild("BackBtn")
    self.bgClose = self:GetChild("bgClose")
    self.scrollTitle = self:GetChild("AllSeverList1")
    self.scrollDetail = self:GetChild("AllSeverList2")
    self.scrollRecommend = self:GetChild("RecSeverList")
    self.ctrlTab = self:GetController("ctrlSelect")
    self:BindEvent()
    self:Initlize()
    self.selectMode = false;
end

function UIServer:OnClose()
    closeUI(PanelResNames.UIServer)
end

function UIServer:SetSelectMode()
    self.selectMode = true
end

function UIServer:Initlize()
    self.serverArr = {}
    self.serverDic = {}
    self.serverDicNum = 0;
    self.allServerDic = {};
    self.allServerDicNum = 0;
    self.curServerInfo = nil
    self.recommendList = nil
    self.actualServer = {}
    self.showNoticeServer = false
    logicMgr.LoginManager.RefreshServerList(true, function()
        self.serverList = logicMgr.LoginManager.GetServerList(); --含区服信息
        self.allServerList = logicMgr.LoginManager.GetAllServerList();
        loginHandler.HttpGetNoticeServerTime(function() loginHandler.HttpGetServerUserList( function(data) self:OnCallBackRecommend(data) end ) end)
        self:SetServerPage()
    end)
end
---服务器列表分页
function UIServer:SetServerPage()
    self.flagList_1 = {}
    for k, v in pairs(self.allServerList) do
        local info = _MServerInfo.New();
        info:Update(k,v);
        table.insert(self.serverArr,info)
    end
    table.sort(self.serverArr,function (a,b)
        if a.showServerId and b.showServerId then
            return a.showServerId < b.showServerId
        end
        return a.time>b.time
    end)
    local num=tonumber(HelperFunc.GetGlobalVlue(593));
    local serverNum = #self.serverArr;
    local showServer = self.serverList["显示列表"];
    local tabNum = math.ceil(table.nums(self.allServerList)/tonumber(HelperFunc.GetGlobalVlue(593)));
    for i = 1,tabNum do
        local flagList = {}
        local allFlagList = {}
        for j = num,1,-1 do
            local index = (i-1) * num + j;
            if index <= serverNum then
                if showServer ~= nil and showServer[tostring(self.serverArr[index].serverId)] then
                    if self.serverArr[index].showServerId then
                        print(self.serverArr[index].showServerId.."==="..self.serverArr[index].name)
                    end
                    table.insert(flagList, self.serverArr[index]);
                end
                table.insert(allFlagList, self.serverArr[index]);
            end
        end
        if #flagList > 0 then
            self.serverDicNum = self.serverDicNum + 1;
            self.serverDic[i] = flagList;
        end
        self.allServerDicNum = self.allServerDicNum + 1;
        self.allServerDic[i] = allFlagList;
    end
    self.ctrlTab.selectedIndex = ENU_TAB.RECOMMEND
    self:OnClickTab()
end

function UIServer:OnEnable()

end

function UIServer:BindEvent()
    self:SetDynamicList(self.scrollTitle, self.UpdateTitleList)
    self:SetDynamicList(self.scrollDetail, self.UpdateDetailList)
    self:SetDynamicList(self.scrollRecommend, self.UpdateRecommendList)
    self:RegisterOnChanged(self.ctrlTab, self.OnClickTab)
    self:RegisterOnClick(self.btnClose, self.OnClose)
    self:RegisterOnClick(self.bgClose, self.OnClose)
end

function UIServer:OnClickTab()
    self:SelectTab(self.ctrlTab.selectedIndex)
end

function UIServer:SelectTab(selectIndex)
    if selectIndex == ENU_TAB.RECOMMEND then
        --loginHandler.HttpGetServerUserList( function(data) self:OnCallBackRecommend(data) end )
    elseif selectIndex == ENU_TAB.ALL then
        --self.scrollTitle.numItems = self:GetTitleCount()
        if logicMgr.LoginManager.isWhiteList then
            self.serverTabNum = self.allServerDicNum;
        else
            self.serverTabNum = self.serverDicNum;
        end
        self.scrollTitle.numItems = self.serverTabNum
        self:SelectTitle(1)
    end
end

--- 区服刷新
function UIServer:UpdateTitleList(index, obj)
    obj.selected=false
    if index==1 then
        selectObj =obj
        selectObj.selected = true
    end
    local txtSeverName = obj:GetChild("SeverName")
    --txtSeverName.text = self:GetTitleInfo(index)
    txtSeverName.text = string.format(getLanguage("ServerTips"),(self.serverTabNum-index+1)*tonumber(HelperFunc.GetGlobalVlue(593)),(self.serverTabNum-index)*tonumber(HelperFunc.GetGlobalVlue(593))+1)
    obj.onClick:Clear()
    obj.onClick:Add(function()
        if obj.selected == true then
            return
        end
        obj.selected = true
        self:OnClickSelectTitle(index)
        selectObj.selected=false
        selectObj=obj
    end)
end

--- 全部服务器列表刷新
function UIServer:UpdateDetailList(index, obj)
    local info = self.curServerInfo[index];
    if info then
        --printError("服务器列表刷新", index, sid)
        --dump(info)
        local serviceName = obj:GetChild("SeverName")
        --local imgIcon = obj:GetChild("Head"):GetChild("HeadIcon")
        local ip = info.ip;
        local port = info.gamePort;
        serviceName.text = info.name;
        if DEBUG then
            serviceName.text = ip
        end
        
        local selectIndex = 0
        local enu = info.state
        if enu == Server_ENU_State.Repair then
            selectIndex = 3
        elseif enu == Server_ENU_State.Full then
            selectIndex = 1
        elseif enu == Server_ENU_State.Fluent then
            selectIndex = 0
        elseif enu == Server_ENU_State.Crowded then
            selectIndex = 5
        end
        local state = obj:GetController("type")
        state.selectedIndex = selectIndex

        if self:CheckServerIsBanned(info.serverId) then
            state.selectedIndex = 4
        end

        obj.onClick:Clear()
        obj.onClick:Add(function()
            self:SelectServer(ip, port, info.name, info.serverId, enu);
        end)
    end

    local ctrShowPlayer = obj:GetController("player")
    ctrShowPlayer.selectedIndex = ENU_CTRL_SHOW.HIDE
    local serverId = info.serverId;
    local serverInfo = self:GetRecommendDetailInfo(serverId)
    if serverInfo then
        local resultInfo = self:GetRecommendInfoForSid(serverId)
        if resultInfo then
            ctrShowPlayer.selectedIndex = ENU_CTRL_SHOW.SHOW
            local headIcon = resultInfo["playerHeadIcon"]
            local heroInfo = dataTable.getRow("t_hero", headIcon)
            if heroInfo then
                local headImage = self:GetChild("HeadIcon/head/icon", obj)
                headImage.url = "ui://ICONAtlas/" .. heroInfo["f_HeroIcon"]
            end
            local txtLevel = self:GetChild("HeadIcon/Text_PlayerLevel", obj)
            txtLevel.text = resultInfo["playerLevel"]

            local txtPower = obj:GetChild("Power")
            txtPower.text = resultInfo["playerPower"]

            local txtPlayerName = obj:GetChild("PlayerName")
            txtPlayerName.text = resultInfo["playerName"]
        end
    end
end

--- http回调 推荐列表服务器
function UIServer:OnCallBackRecommend(data)
    local count = 0
    if data then
        self.recommendList = data["recordList"]
        if self.recommendList then
            --count = #self.recommendList
            for i, v in pairs(self.recommendList) do
                if v then
                    local info = self:GetRecommendDetailInfo(v.serverId)
                    if info then
                        count = count + 1
                        table.insert(self.actualServer,v)
                    end
                end
            end
        end
    end

    self.showNoticeServer = logicMgr.LoginManager.GetNoticeServerTime() - HelperFunc.GetServerTime() > 0
    if self.showNoticeServer then
        count = count + 1
        table.insert(self.actualServer,1, logicMgr.LoginManager.GetNoticeServerTime())
    end
    self.scrollRecommend.numItems = count
end

--- 推荐服务器列表刷新
function UIServer:UpdateRecommendList(index, obj)
    local info = self.actualServer[index]
    local state = obj:GetController("type")
    local ctrShowPlayer = obj:GetController("player")
    local serviceName = obj:GetChild("SeverName")
    ctrShowPlayer.selectedIndex = ENU_CTRL_SHOW.HIDE

    if self.showNoticeServer and index == 1 then
        --开服预览置顶显示（特殊显示）
        state.selectedIndex = 2
        local showText = string.format(getLanguage("Login_Tips_02"), tostring(os.date("%Y-%m-%d %H:%M", info)))
        serviceName.text = showText
        obj.onClick:Add(function()
            UISysTips.AddMsg(showText)
        end)
    else
        local serverId = info["serverId"]

        if serverId == AppConst.ServerId then
            --本服角色使用本地数据，保证最新，如果是白名单功能显示的，还是用redis数据
            if logicMgr.HeroManager.GetRoleName() ~= "" then
                info["playerLevel"] = logicMgr.HeroManager.GetRoleLevel()
                info["playerName"] = logicMgr.HeroManager.GetRoleName()
                info["playerHeadIcon"] = logicMgr.HeroManager.GetRoleHeadID()
            end
        end

        local selectIndex = 1
        local serverInfo = self:GetRecommendDetailInfo(serverId)
        if serverInfo then
            ctrShowPlayer.selectedIndex = ENU_CTRL_SHOW.SHOW

            local txtPlayerName = obj:GetChild("PlayerName")
            txtPlayerName.text = info["playerName"]

            local txtPower = obj:GetChild("Power")
            txtPower.text = info["playerPower"]

            local txtLevel = self:GetChild("HeadIcon/Text_PlayerLevel", obj)
            txtLevel.text = info["playerLevel"]

            local headIcon = info["playerHeadIcon"]
            local heroInfo = dataTable.getRow("t_hero", headIcon)
            if heroInfo then
                local headImage = self:GetChild("HeadIcon/head/icon", obj)
                headImage.url = "ui://ICONAtlas/" .. heroInfo["f_HeroIcon"]
            end

            obj.onClick:Clear()

            local ip = serverInfo[Server_ENU_INDEX.IP]
            local port = serverInfo[Server_ENU_INDEX.PORT]
            serviceName.text = serverInfo[Server_ENU_INDEX.NAME]
            if DEBUG then
                serviceName.text = ip
            end
            local enu = serverInfo[Server_ENU_INDEX.STATE]
            if enu == Server_ENU_State.Repair then
                selectIndex = 3
            elseif enu == Server_ENU_State.Full then
                selectIndex = 1
            elseif enu == Server_ENU_State.Fluent then
                selectIndex = 0
            elseif enu == Server_ENU_State.Crowded then
                selectIndex = 5
            end
            obj.onClick:Add(function()
                self:SelectServer(ip, port, serverInfo[Server_ENU_INDEX.NAME], serverId, enu)
            end)
        end
        if self:CheckServerIsBanned(serverId) then
            selectIndex = 4
        end
        state.selectedIndex = selectIndex
    end
end

function UIServer:CheckServerIsBanned(serverId)
    local banned = logicMgr.LoginManager.GetBannedState()
    if banned and banned.banned == 1 then
        if tonumber(serverId) == logicMgr.LoginManager.GetLastServerId() then
            return true
        end
    end
    return false
end

--- 点击选择区服
function UIServer:OnClickSelectTitle(index)
    self:SelectTitle(index)
end

function UIServer:SelectTitle(index)
    if logicMgr.LoginManager.isWhiteList then
        self.curServerInfo = self.allServerDic[self.serverTabNum - index + 1];
    else
        self.curServerInfo = self.serverDic[self.serverTabNum - index + 1];
    end
    if self.curServerInfo ~= nil then
        self.scrollDetail.numItems = table.nums(self.curServerInfo)
    end
end

--- 选择服务器
function UIServer:SelectServer(ip, port, content,id, serverSate)
    if self:CheckServerIsBanned(id) then
        UISysTips.AddMsg(getLanguage("Sys_MsgBanned"))
        return
    end

    if self.selectMode then

        local info = logicMgr.LoginManager.GetServerInfo(tonumber(id))
        if info then
            logicMgr.LoginManager.SetDefaultServerInfo(info);
        end

        Config.lastLoginServerId = AppConst.ServerId;
        Config.DefaultServerId = tonumber(id)
        AppConst.ServerId = tonumber(id)
        closeUI(PanelResNames.UIServer)
        CtrlManager.GetCtrl(PanelNames.UILogin):Refresh()
        return
    end

    if serverSate ~= nil and serverSate == Server_ENU_State.Repair then
        UISysTips.AddMsg(getLanguage("MaintenanceMsg_Title_Maintenance"))
        return
    end

    if tostring(logicMgr.LoginManager.GetLoginRecordIP()) == tostring(ip) and tonumber(logicMgr.LoginManager.GetLoginRecordPort()) == tonumber(port) and tonumber(AppConst.ServerId) == tonumber(id) then
        UISysTips.AddMsg(getLanguage("Sys_MsgSameSever"))
        return
    end
    local info = logicMgr.LoginManager.GetServerInfo(tonumber(id))--self.curServerInfo[index]
    if info then
        LoginManager.LoginServer(info,function()
            local ctrl = CtrlManager.GetCtrl(PanelNames.UICommonPop)
            ctrl.Init("27", function(b)
                if b then
                    --LoginSDK.GetInstance():LoginOutU8SDK()
                    Config.lastLoginServerId = AppConst.ServerId;
                    Config.ChangeServer = true
                    Config.DefaultServerId = tonumber(id)
                    AppConst.ServerId = tonumber(id)
                    --logicMgr.LoginManager.SetAutoLogin(true)
                    logicMgr.LoginManager.SetDefaultServerInfo(info)

                    Game.ResetStart(true)
                end
            end, content);
        end,true)
    else
        UISysTips.AddMsg(getLanguage("ErrorCode_100004"));
    end
    
end

function UIServer:GetRecommendInfoForSid(serverId)
    if self.recommendList then
        for _, v in pairs(self.recommendList) do
            if tostring(v["serverId"]) == tostring(serverId) then
                return v
            end
        end
    end
end

--- 已存在角色的服务器列表
function UIServer:GetRecommendDetailInfo(index)
    if self.allServerList then
        return self.allServerList[tostring(index)]
    end
end

return UIServer;